<template>
  <div>
    <el-card style="margin:15px 0px">
      <CategorySelect @getInfoList="getAttrInfoList" :show="!isShowTable"></CategorySelect>
    </el-card>

    <el-card>
      <div v-show="isShowTable">
        <el-button type="primary" icon="el-icon-plus" :disabled="!category3Id" @click="addAttr">添加属性</el-button>
        <el-table style="width: 100%" border :data="attrList">
          <el-table-column type="index" label="序号" width="80" align="center">
          </el-table-column>
          <el-table-column prop="attrName" label="属性名称" width="150">
          </el-table-column>
          <el-table-column prop="prop" label="属性值列表" width="width">
            <template slot-scope="{row,$index}">
              <el-tag type="success" v-for="(attrItem, index) in row.attrValueList" :key="attrItem.id"
                style="margin:0px 10px;">{{ attrItem.valueName }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="prop" label="操作" width="150">
            <template slot-scope="{row,$index}">
              <el-button type="warning" icon="el-icon-edit" size="mini" @click="updateAttr(row)" style="margin-right:10px;"></el-button>

              <el-popconfirm :title="`确定删除属性：${row.attrName}吗？`" @onConfirm="deleteAttrById(row.id)">
                <el-button type="danger" icon="el-icon-delete" size="mini" slot="reference"></el-button>
              </el-popconfirm>


              <!-- <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteAttrById(row.id)"></el-button> -->
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-show="!isShowTable">
        <el-form :inline="true" ref="form" :model="attrInfo" label-width="80">
          <el-form-item label="属性名">
            <el-input placeholder="请输入属性名" v-model="attrInfo.attrName"></el-input>
          </el-form-item>
        </el-form>
        <el-button type="primary" icon="el-icon-plus" @click="addAttrValue"
          :disabled="!attrInfo.attrName.trim()">添加属性值</el-button>
        <el-button @click="isShowTable = true">取消</el-button>
        <el-table border :data="attrInfo.attrValueList" style="width: 100%; margin:20px 0px;">
          <el-table-column type="index" align="center" label="序号" width="80">
          </el-table-column>
          <el-table-column prop="prop" label="属性值名称" width="width">
            <template slot-scope="{row, $index}">
              <el-input v-if="row.flag" :ref="$index" v-model="row.valueName" placeholder="请输入属性值名称" size="mini"
                @blur="toLook(row)" @keyup.native.enter="toLook(row)"></el-input>
              <span v-else @click="toEdit(row, $index)" style="display:block">{{ row.valueName }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="prop" label="操作" width="width">
            <template slot-scope="{row, $index}">
              <el-popconfirm :title="`确定删除属性值：${row.valueName}吗？`" @onConfirm="deleteAttrValue($index)">
                <el-button type="danger" icon="el-icon-delete" size="mini" slot="reference"></el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" @click="addOrUpdateAttr" :disabled="attrInfo.attrValueList.length<1">保存</el-button>
        <el-button @click="isShowTable = true">取消</el-button>

      </div>

    </el-card>
  </div>
</template>

<script>
import cloneDeep from 'lodash/cloneDeep'
export default {
  name: 'Attr',
  data() {
    return {
      category1Id: '',
      category2Id: '',
      category3Id: '',
      attrList: [],
      isShowTable: true,
      attrInfo: {

        attrName: "",
        attrValueList: [
          // {
          //   valueName:"",
          //   attrId:0
          // }
        ],
        categoryId: 0,
        categoryLevel: 3,
      }
    }


  },
  methods: {
    async getAttrInfoList({ category1Id, category2Id, category3Id }) {
      //根据category2Id,category3Id是否为空进行判断
      this.category1Id = category1Id
      this.category2Id = category2Id
      this.category3Id = category3Id
      this.isShowTable = true
      if (category2Id != '' && category3Id != '') {
        let result = await this.$API.attr.reqGetAttrInfoList(category1Id, category2Id, category3Id)
        if (result.code == 200) {
          this.attrList = result.data
        }
      } else {
        this.attrList = []
      }
    },
    addAttrValue() {
      this.attrInfo.attrValueList.push(
        {
          valueName: '',
          attrId: this.attrInfo.id,
          flag: true
        }
      )
      this.$nextTick(() => {
        this.$refs[this.attrInfo.attrValueList.length - 1].focus()
      })

    },
    addAttr() {
      this.attrInfo = {
        attrName: "",
        attrValueList: [
        ],
        categoryId: this.category3Id,
        categoryLevel: 3,
      }
      this.isShowTable = false
    },
    updateAttr(row) {
      this.isShowTable = false
      this.attrInfo = cloneDeep(row)
      // console.log(row);
      this.attrInfo.attrValueList.forEach(item => this.$set(item, 'flag', false))

    },
    //删除商品属性
    async deleteAttrById(id){
      try {
        const result = await this.$API.attr.reqDeleteAttrById(id)
        if(result.code == 200){
          this.$message({type:'success',message:'删除成功'})
          this.getAttrInfoList({ category1Id:this.category1Id, category2Id:this.category2Id, category3Id:this.category3Id })
        }
      } catch (error) {
        this.$message('删除失败')
        this.getAttrInfoList({ category1Id:this.category1Id, category2Id:this.category2Id, category3Id:this.category3Id })
      }
    },
    //切换查看模式
    toLook(row) {
      // 处理用户的输入
      if (row.valueName.trim() == '') {
        this.$message('输入不能为空！')
        return
      }
      const isRepet = this.attrInfo.attrValueList.some(item => {
        if (row !== item) {
          return row.valueName == item.valueName
        }
      })
      if (isRepet) {
        this.$message('输入不能出现重复')
        return
      }

      row.flag = false
    },
    // 点击span的回调，变为编辑模式，光标自动 聚焦
    toEdit(row, index) {
      row.flag = true
      //获取input并聚集
      this.$nextTick(() => {
        this.$refs[index].focus()
      })
    },
    //气泡确定按钮的回调
    deleteAttrValue(index){
      // 当前删除操作不需要发请求
      this.attrInfo.attrValueList.splice(index, 1)
    },

    //保存按钮，添加或者修改属性
    async addOrUpdateAttr(){
      this.attrInfo.attrValueList = this.attrInfo.attrValueList.filter(item=>{
        if(item.valueName.trim()!=''){
          delete item.flag
          return true
        }
      })
      if(this.attrInfo.attrValueList.length > 0){
        //发请求
        try {
          console.log();
          await this.$API.attr.reqAddOrUpdateAttr(this.attrInfo)
          this.$message({type:'success', message:'保存成功'})
          this.isShowTable = true
          this.getAttrInfoList({ category1Id:this.category1Id, category2Id:this.category2Id, category3Id:this.category3Id })
        } catch (error) {
          this.$message('保存失败')
        }
      }else{
        this.$message('保存失败')
      }

    }

  }

}
</script>

<style></style>
